var $ = require('jquery');
var url = require('url');
var http = require('http');
var iconv = require('iconv-lite')
var webInterface = require('./webInterface');
var log4js = require('log4js');
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('logs/mealPromotion.log'),
		'mealPromotion');
var logger = log4js.getLogger('mealPromotion');

// var tbskipMealUrl =
// "http://tbskip.daily.taobao.net/json/promotion.htm?callback=jsonpInitExtension&user_id=2033188194&item_id=1500024764290&meal=1&tmall=1";
var defaultCallback = 'TShop.mods.SKU.Promotion.getDefaultData';
var mdskipMealApi = "http://mdskip.taobao.com/extension/initExtension.htm";
exports.mdskipApi = mdskipMealApi;
exports.tbskipApi = 'http://tbskip.taobao.com/json/promotion.htm';

var tbskipCallback = function(jsonObj) {

	return getMealList(jsonObj.data)
}

function getMealList(mealDom) {
	var $dom = $(mealDom);
	var mealList = new Array();

	$dom.find('ol#J_ComboPage.tb-pagination li a').each(
			function(i, ele) {
				var $ele = $(ele);
				if ($ele.attr('class').indexOf('tb-prev') >= 0
						|| $ele.attr('class').indexOf('tb-next') >= 0) {
					return;
				}
				var meal = {};

				var mealdata = $ele.attr('data-mealdata')
				var mealid = mealdata.substring(0, mealdata.indexOf('|'));
				meal[mealid] = mealdata;
				mealList.push(meal);
			})

	return mealList;
}

var mdskipCallback = function(jsonObj) {
	return getMealList(jsonObj.mealResult)
}

exports.verify = function(tbskipMealUrl, callback) {
//	logger.error('readUrl:	' + tbskipMealUrl);
	var originalTbskipUrl = tbskipMealUrl;
	tbskipMealUrl = prepareTbskipUrl(tbskipMealUrl);
	var mdskipMealUrl = convertTbskipMealApiToMdskipMealApi(tbskipMealUrl)

	webInterface.sendRequest(mdskipMealUrl, tbskipMealUrl, function(mdskipres,
			tbskipres) {
		try {
//			logger.error(mdskipres);
//			logger.error(tbskipres);
			tbskipres = tbskipres.replace(/\\"/g, "\"");
			var tbskipMealList = eval(tbskipres);
			var mdskipMealList = eval(mdskipres);
			var isEqual = compareMealList(tbskipMealList, mdskipMealList, mdskipMealUrl, tbskipMealUrl);
			if (!isEqual) {
				logger.error("NotEqual	" + mdskipMealUrl + "		" + tbskipMealUrl);
			} else {
				logger.error('equals');
			}
		} catch (e) {
			logger.error("Exception:" + mdskipMealUrl + "	" + tbskipMealUrl + "    " + originalTbskipUrl, e);
		}
		if ((typeof callback != 'undefined') && callback != null) {
			callback();
		}
	});
}

function prepareTbskipUrl(tbskipMealUrl) {
	if (tbskipMealUrl.indexOf(defaultCallback) > 0) {
		tbskipMealUrl = tbskipMealUrl
				.replace(defaultCallback, 'tbskipCallback')
	}else if (tbskipMealUrl.indexOf('jsonpInitExtension') > 0) {
		tbskipMealUrl = tbskipMealUrl.replace('jsonpInitExtension' , 'tbskipCallback')
	}
	return tbskipMealUrl;
}

function convertTbskipMealApiToMdskipMealApi(tbskipurl) {

	var tbskipRequest = url.parse(tbskipurl);

	var tbskipParams = parseQueryString(tbskipRequest.query);

	var mdskipMealUrl = mdskipMealApi + "?";

	for ( var key in tbskipParams) {
		var value = tbskipParams[key];
		if (key == "user_id") {
			mdskipMealUrl = mdskipMealUrl + "sellerId=" + value + "&";
		} else if (key != "callback") {
			mdskipMealUrl = mdskipMealUrl + key + '=' + value + '&'
		}
	}

	mdskipMealUrl = mdskipMealUrl + 'callback=mdskipCallback&debug=true';
	return mdskipMealUrl;
}

function compareMealList(list1, list2, mdskipMealUrl, tbskipMealUrl) {
	if (list1.length != list2.length) {
		return false;
	}
	var map1 = {};
	var map2 = {};
	for ( var i = 0; i < list1.length; i++) {
		var value1 = list1[i];
		for ( var key in value1) {
			map1[key] = value1[key];
		}
		var value2 = list2[i];
		for ( var key in value2) {
			map2[key] = value2[key];
		}
	}
	
	for (var key in map1) {
		var value1 = map1[key]
		var value2 = map2[key]
		if (value1 != value2) {
			if(list1.length == 5){
				logger.error("NotEqualBut5	" + mdskipMealUrl + "		" + tbskipMealUrl);
				return true;
			}
//			logger.error(key + ': ' + value1 + '	' + value2)
			return false;
		}
	}
	return true;
}

function parseQueryString(queryString) {
	var params = {};

	var paramPv = queryString.split('&');
	for ( var i = 0; i < paramPv.length; i++) {
		var pvString = paramPv[i];
		var pvPair = pvString.split('=');
		params[pvPair[0]] = pvPair[1];
	}
	return params;
}